//
//  StoresInfoController.m
//  NPS
//
//  Created by jadd on 15/10/12.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "StoresInfoController.h"

@implementation StoresInfoController
@synthesize myTableView,mybuttonTableView;
@synthesize listData,storeId;
@synthesize button;
@synthesize customAlertView;
@synthesize isAdd;
@synthesize deleteIndex;

// 添加店铺事件
-(IBAction)addStoreAction:(id)sender
{
    customAlertView  = [self createAlertView:@"输入店铺名称" FieldTxt:@"" Placeholder:@"请输入店铺名称" CancelBtnTitle:@"取消" OtherBtnTitles:@"保存" Tag:10000];
    [customAlertView show];
}

#pragma mark - 按钮触发事件 (二维码)
- (void)QRcodebuttonAction:(UIButton *)sender
{
    if (sender && [sender respondsToSelector:@selector(superview)]) {
        
        // 根据点击的button找到对应的comment数据模型
        UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
        
        NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
        
        if (indexPath == nil) {
            // iOS7
            indexPath = [self.myTableView indexPathForCell:(UITableViewCell *)cell.superview];
        }
        StoreModel *obj = [self.listData objectAtIndex:indexPath.section];
        QRCodeController *controller = [[QRCodeController alloc] init];
        controller.store = obj;
        [self.navigationController pushViewController:controller animated:YES];
   
    }
}

//删除店铺 2015-12-10 Jadd
-(void) deleteAlert: (NSUInteger) index
{
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:@"确定要删除吗?" delegate:self
                                           cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil];
    [as showInView:[UIApplication sharedApplication].keyWindow];
    //[as release];
    
}


-(void) actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        
        [self.listData removeObjectAtIndex:0];
        [self.myTableView reloadData];
        //[self.myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:self.deleteIndex] withRowAnimation:UITableViewRowAnimationFade];
        NSLog(@"删除");
    }
}


//修改店铺的名称 2015-12-10
-(void) labelTouchUpInside:(UITapGestureRecognizer *)recognizer{
    UILabel *label = (UILabel*)recognizer.view;
    UITableViewCell *cell = (UITableViewCell *)label.superview;
    
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    
    if (indexPath == nil) {
        // iOS7
        indexPath = [self.myTableView indexPathForCell:(UITableViewCell *)cell.superview];
    }
    StoreModel *model = [listData objectAtIndex:indexPath.section];
    self.storeId = model.storeId;
    
    
    customAlertView  = [self createAlertView:@"修改店铺名称" FieldTxt:model.name Placeholder:nil CancelBtnTitle:@"取消" OtherBtnTitles:@"保存" Tag:20000];
    
    [customAlertView show];

    
}


#pragma mark - 修改店铺的名称
- (void)ModifyStoreNameAction:(UILabel *)sender
{
    if (sender && [sender respondsToSelector:@selector(superview)]) {
        
        // 根据点击的button找到对应的comment数据模型
        UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
        
        NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
        
        if (indexPath == nil) {
            // iOS7
            indexPath = [self.myTableView indexPathForCell:(UITableViewCell *)cell.superview];
        }
        StoreModel *model = [listData objectAtIndex:indexPath.section];
        self.storeId = model.storeId;
        
        
        customAlertView  = [self createAlertView:@"修改店铺名称" FieldTxt:model.name Placeholder:nil CancelBtnTitle:@"取消" OtherBtnTitles:@"保存" Tag:20000];
        
        [customAlertView show];
    }
}

// 我的账户设置
-(IBAction)Myaccount:(id)sender{
    AccountSettingController *controller = [[AccountSettingController alloc] initWithStyle:UITableViewStyleGrouped];
    //[self.navigationController pushViewController:controller animated:YES];
    
    
    NSString *link = @"";
    
    for (int i = 0; i < [self.listData count]; i++) {
        StoreModel *model =[self.listData objectAtIndex:i];
        if(model.surveyLink != nil && ![model.surveyLink isEqualToString:@""])
        {
            link = model.surveyLink;
            break;
        }
    }
    controller.URL = [NSURL URLWithString:link];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:nav animated:YES completion:^{
        NSLog(@"");
    }];
    
//    UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    ModifyPasswdViewController*secondController = [mainStory instantiateViewControllerWithIdentifier:@"ModifyPwdVC"];
//    [self.navigationController pushViewController:secondController animated:YES];
//    SecondViewController * controller = [[SecondViewController alloc] initWithStyle:UITableViewStyleGrouped];
//
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        
        UITextField *nameField = [alertView textFieldAtIndex:0];
        NSString *key = @"";
        key = [nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if(alertView.tag == 10000)
        {
            [self addStores:key];
           
        }
        if(alertView.tag == 20000)
        {
            [self modifyStores:key StoreId:self.storeId];
        }
        nameField.text = nil;
        
    }
    if(buttonIndex == 0)
    {
        UITextField *nameField = [alertView textFieldAtIndex:0];
        nameField.text = nil;
    }
}

//修改店铺名称事件
-(void) modifyStores:(NSString *) storeName StoreId:(NSString *)store_Id
{
    [Config showActivityView];
    ModifyStoreNameRequest *request = [[ModifyStoreNameRequest alloc] initWithUserId:[Config getUser_id] Name:storeName StoreId:store_Id];
    
    [RequestHandle startOperationWithRequest:request
                                    complete:^(id responseObject) {
                                        
                                        ModifyStoreNameReponse * response = [[ModifyStoreNameReponse alloc] init];
                                        response.responseObject = responseObject; 
                                        if([[responseObject objectForKey:@"status"] isEqualToString:@"success"])
                                        {
                                            
                                            [self getStoresInfo];
                                        }
                                        [Config hideActivityView];
                                        while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
                                        
                                    } error:^(NSError *error) {
                                        [Config hideActivityView];
                                        [Config showMessage:error.localizedDescription];
                                        
                                        
                                    }];
}


//添加店铺事件
-(void) addStores:(NSString *) storeName
{
    [Config showActivityView];
    AddStoreRequest *request = [[AddStoreRequest alloc] initWithUserId:[Config getUser_id] Name:storeName];
    
    [RequestHandle startOperationWithRequest:request
                                    complete:^(id responseObject) {
                                        
                                        AddStoreReponse * response = [[AddStoreReponse alloc] init];
                                        response.responseObject = responseObject; //保存数据
                                        if([[responseObject objectForKey:@"status"] isEqualToString:@"success"])
                                        {
                                            //添加店铺成功
                                            isAdd = true;
                                            [self getStoresInfo];
                                        }
                                        else
                                        {
                                            isAdd = false;
                                        }
                                        [Config hideActivityView];
                                        
                                        while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
                                    
                                    } error:^(NSError *error) {
                                        
                                        [Config hideActivityView];
                                       
                                        [Config showMessage:error.localizedDescription];
                                        
                                        
                                    }];
}

//获取店铺列表
-(void) getStoresInfo
{
    [Config showActivityView];
    StoresRequest * request = [[StoresRequest alloc] initWithUserId:[Config getUser_id]];
    
    [RequestHandle startOperationWithRequest:request
                                    complete:^(id responseObject) {
                                        
                                        StoresReponse * response = [[StoresReponse alloc] init];
                                        response.responseObject = responseObject; //保存数据
                                        
                                        self.listData = [MyGlobal sharedVariables].storesArray;
                                        [Config hideActivityView];
                                        if([listData count] == 0)
                                        {
                                            customAlertView  = [self createAlertView:@"输入店铺名称" FieldTxt:@"" Placeholder:@"请输入店铺名称" CancelBtnTitle:@"取消" OtherBtnTitles:@"保存" Tag:10000];
                                            [customAlertView show];
                                        }
                                        else
                                        {
                                            [self.myTableView reloadData];
                                            if(isAdd)
                                            {
                                                StoreModel *obj = [self.listData objectAtIndex:0];
                                                QRCodeController *controller = [[QRCodeController alloc] init];
                                                controller.store = obj;
                                                [self.navigationController pushViewController:controller animated:YES];
                                            }
                                        }
                                        //[GMDCircleLoader hideFromView:self.view animated:YES];
                                        while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
                                     
                                    } error:^(NSError *error) {
                                        [Config hideActivityView];

                                        if(error.code == ERROR_PARA_VERIFIY)
                                        {
                                            [MyGlobal sharedVariables].isReLogin = YES;
                                        }
                                        
                                        //[Config showMessage:error.localizedDescription];
                                        
                                    }];
    
}


/*
  先获取店铺列表，如没有店铺信息就弹出添加店铺信息，先执行信息添加，添加成功以后，
    重新获取店铺列表，然刷新界面
 */
- (void)viewDidLoad {
    
    listData = [[NSMutableArray alloc] init];

    self.edgesForExtendedLayout = UIRectEdgeNone;
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
    self.title = @"店 铺";
    UIBarButtonItem *regBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhanghu"] style:UIBarButtonItemStylePlain target:self action:@selector(Myaccount:)];
    self.navigationItem.rightBarButtonItem = regBtn;
    //影藏返回按按钮
    self.navigationItem.hidesBackButton = YES;
    //6p 736,414;
    //i6 667,375
    //i5 568,320
    //i4 489,320
    
    [self getStoresInfo];
    [self getViewInit];
    [self setupMJRefresh];
    [super viewDidLoad];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


-(void) viewWillAppear:(BOOL)animated
{
    //没有登录
    if(![Config hasLogin] && [MyGlobal sharedVariables].needLoad)
    {
        [self getStoresInfo];
        [MyGlobal sharedVariables].needLoad = NO;
        
//        [self dismissViewControllerAnimated:YES completion:^{
//            NSLog(@"");
//        }];
    }
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [super viewWillAppear:YES];
}


-(void) viewWillDisappear:(BOOL)animated
{
    isAdd = false;
    [super viewWillDisappear:YES];
}

-(void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

}

- (void) doMJRefreshHandle {
    
    [myTableView headerEndRefreshing];
    [self getStoresInfo];
}


//下拉刷新
- (void)setupMJRefresh
{
    
    //[myTableView addHeaderWithTarget:self action:@selector(doMJRefreshHandle) dateKey:@"table"];
    [myTableView addHeaderWithTarget:self action:@selector(doMJRefreshHandle)];
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    //myTableView.headerPullToRefreshText = @"下拉可以刷新";
    //myTableView.headerReleaseToRefreshText = @"松开立即刷新";
    myTableView.headerRefreshingText = @"刷新中。。。";

    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //[myTableView addFooterWithTarget:self action:@selector(footerRereshing)];

}


-(void) getViewInit{
    
    CGRect rect;
    rect = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 140);
    
    myTableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStyleGrouped];
    //右边滚动条是否显示
    [myTableView setShowsVerticalScrollIndicator:NO];
     myTableView.delaysContentTouches = NO;
    myTableView.delegate = self;
    myTableView.dataSource = self;
    //UITableView 去除空的Cell
    myTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    [myTableView registerClass:[StoreCell class] forCellReuseIdentifier:@"TJCell"];
    [self.view addSubview:myTableView];
    
    
     rect = CGRectMake(0, self.view.bounds.size.height - 145, K_ScreenWidth, 82.0f);
     UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 145, K_ScreenWidth, 82.0f)];
     footView.backgroundColor = BACK_VIEW_COLOR;
     footView.tintColor = CLEAR;
     
     
     button = [UIButton buttonWithType:UIButtonTypeSystem];
     [button setFrame:CGRectMake(K_ScreenWidth *0.04, 15, (K_ScreenWidth -(K_ScreenWidth *0.04*2)), 45.0f)];
     
     [button.layer setMasksToBounds:YES];
     [button.layer setCornerRadius:5.0f];
     [button.layer setBorderWidth:0.5f];
     [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
     button.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
    
    
     UIFont *font = [UIFont systemFontOfSize:18.0];
     UIFont *font2= [UIFont systemFontOfSize:20.0];
     
     NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"+ 添加店铺"];
     
     [string addAttribute:NSForegroundColorAttributeName value:WHITE range:NSMakeRange(0, string.length)];
     [string addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 1)];
     [string addAttribute:NSFontAttributeName value:font2 range:NSMakeRange(1, string.length-1)];
     [button setAttributedTitle:string forState:UIControlStateNormal];
    
     [button addTarget:self action:@selector(addStoreAction:) forControlEvents:UIControlEventTouchUpInside];
     
     [footView addSubview:button];
     [self.view addSubview:footView];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //NSLog(@"%lu",(unsigned long)[self.listData count]);
    return [self.listData count];
    
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
 
    return 1;
   
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    return 135;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   
    if (section == 0) {
        return 20;
    }
    return 5.0f;
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        self.deleteIndex = indexPath;

        [self deleteAlert:[indexPath row]];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *identifier = @"TJCell";
    
    StoreCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[StoreCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    
    NSUInteger section = [indexPath section];
    [cell setLabelText:[self.listData objectAtIndex:section]];
    cell.nameLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside:)];
    
    [cell.nameLabel addGestureRecognizer:labelTapGestureRecognizer];
    
    [cell.modofyBtn addTarget:self action:@selector(ModifyStoreNameAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.QRcodeBtn addTarget:self action:@selector(QRcodebuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
    return nil;
}


#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger section = [indexPath section];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    StoreModel *reportModel = [self.listData objectAtIndex:section];
    ReportViewController *controller = [[ReportViewController alloc] init];

    controller.link = reportModel.report_auth;
    controller.shareLink = reportModel.reportLink;
    controller.name = reportModel.name;
    [self.navigationController pushViewController:controller animated:YES];
    
}

-(UIAlertView *) createAlertView:(NSString *) title FieldTxt:(NSString *) fieldTxt Placeholder:(NSString *) placeholder CancelBtnTitle:(NSString *) cancelBtnTitle OtherBtnTitles: (NSString *) otherBtnTitles Tag: (NSUInteger)tag{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: title message:nil delegate:self cancelButtonTitle:cancelBtnTitle otherButtonTitles:otherBtnTitles, nil, nil];
    alertView.tag = tag;
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];

    UITextField *nameField = [alertView textFieldAtIndex:0];
    nameField.text = fieldTxt;
    nameField.placeholder = placeholder;
    return alertView;
}

@end
